<template>
  <div class="app-container">
    <el-table
      :data="list"
      v-loading="listLoading"
      style="width: 100%"
      row-key="id"
      border
      lazy
      :load="load"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column prop="name" label="名称" width="180"></el-table-column>
      <el-table-column prop="dictCode" label="编码" width="180"></el-table-column>
      <el-table-column prop="value" label="值" width="180"></el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180"></el-table-column>
    </el-table>

    <div style="margin-top:10px">
      <el-button type="primary" @click="upload()">
        上传
        <i class="el-icon-upload2 el-icon--right"></i>
      </el-button>
      <el-button type="warning" @click="download()">
        下载
        <i class="el-icon-download el-icon--right"></i>
      </el-button>
    </div>

    <el-dialog title="上传" :visible.sync="dialogImportVisible" width="480px">
      <el-form label-position="right" label-width="170px">
        <el-form-item label="文件">
          <el-upload
            :multiple="false"
            :on-success="onUploadSuccess"
            :action="'http://localhost:8202/admin/cmn/dict/upload'"
            class="upload-demo"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传xls文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogImportVisible = false">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import dict from "@/api/dict";

export default {
  data() {
    return {
      list: [],
      listLoading: true,
      dialogImportVisible: false,
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    //上传后的回调函数
    onUploadSuccess(response) {
      if (response.code == 20000) {
        this.$message.success("上传成功");
        this.dialogImportVisible = false;

        //加载第一层数据
        this.fetchData();
      } else {
        this.$message.error(response.message);
      }
    },
    //上传excel文件
    upload() {
      //显示弹出层
      this.dialogImportVisible = true;
    },
    //下载excel文件
    download() {
      //打开浏览器标签页，下载文件
      window.open("http://localhost:8202/admin/cmn/dict/download");
    },
    //加载子数据
    load(tree, treeNode, resolve) {
      dict.getByParentId(tree.id).then((response) => {
        //resolve添加到下一层
        resolve(response.data.list);
      });
    },
    //加载列表
    fetchData() {
      dict.getByParentId(1).then((response) => {
        this.list = response.data.list;

        this.listLoading = false;
      });
    },
  },
};
</script>
